import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STColumn, STColumnTag, STComponent, STModule, STPage } from '@delon/abc/st';
import { DelonFormModule } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzFormatEmitEvent } from 'ng-zorro-antd/tree';
import { Api } from 'src/app/shared/api';
import { ResponseCode } from 'src/app/shared/response.code';

import { GroupComponent } from './group.component';
import { UserEditComponent } from './user-edit.component';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['user.component.less'],
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: true,
  imports: [
    PageHeaderModule,
    NzCardModule,
    STModule,
    NzTagModule,
    FormsModule,
    NzButtonModule,
    NzGridModule,
    NzInputModule,
    NzButtonModule,
    NzTagModule
  ]
})
export class UserComponent implements OnInit {
  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private modalService: NzModalService,
    private msg: NzMessageService
  ) {}
  userPage: any = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  userPagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  groupPage: any = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  groupPagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  USER_STATUS_TAG: STColumnTag = {
    true: { text: '启用', color: 'green' },
    false: { text: '禁用', color: 'red' }
  };
  USER_ROLE_TAG: STColumnTag = {
    ADMIN: { text: '管理员', color: 'red' },
    USER: { text: '用户', color: 'green' }
  };
  userParams: any = { current: 1, size: 10 };
  groupParams: any = { current: 1, size: 10 };
  currentGroup: any = {};
  @ViewChild('group', { static: false }) private group!: STComponent;
  @ViewChild('user', { static: false }) private user!: STComponent;
  userColumns: STColumn[] = [
    { title: '编号', type: 'no', width: 80 },
    { title: '用户名', index: 'account' },
    { title: '姓名', index: 'name' },
    { title: '组', render: 'groupName' },
    { title: '角色', index: 'role', type: 'tag', tag: this.USER_ROLE_TAG, width: 100 },
    { title: '状态', index: 'active', type: 'tag', tag: this.USER_STATUS_TAG, width: 80 },
    {
      title: '',
      width: 200,
      buttons: [
        {
          text: '编辑',
          type: 'modal',
          modal: {
            component: UserEditComponent
          },
          click: e => this.queryUser(null)
        },
        {
          text: '禁用',
          type: 'link',
          iif: record => record.active,
          click: e => this.changeUserStatus(e.id, !e.active)
        },
        {
          text: '启用',
          type: 'link',
          iif: record => !record.active,
          click: e => this.changeUserStatus(e.id, !e.active)
        },
        {
          text: '重置密码',
          type: 'link',
          pop: '确认重置该用户的密码吗',
          click: e => this.resetUserPassword(e)
        },
        {
          text: '删除',
          type: 'del',
          click: e => this.deleteUser(e)
        }
      ]
    }
  ];
  groupColumns: STColumn[] = [
    { index: 'id', type: 'radio', width: 30 },
    { title: '编号', type: 'no', width: 80 },
    { title: '名称', index: 'name' },
    {
      width: 100,
      buttons: [
        {
          type: 'modal',
          icon: 'edit',
          modal: {
            component: GroupComponent
          },
          click: e => this.queryGroup(null)
        },
        {
          type: 'del',
          icon: 'delete',
          click: e => this.deleteGroup(e)
        }
      ]
    }
  ];
  ngOnInit() {
    this.queryGroup(null);
    this.queryUser(null);
  }
  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
  }

  groupChange(event: any) {
    console.log(event);
    if (event) {
      if (event.type === 'ps') {
        this.groupParams.size = event.ps;
        this.queryGroup(null);
      }
      if (event.type === 'radio') {
        this.currentGroup = event.radio;
        this.queryUser(event.radio);
      }
    }
  }

  resetGroup() {
    this.group.reset();
    this.currentGroup = {};
    this.groupParams = {};
    delete this.userParams.groupId;
    this.queryUser(null);
  }

  resetUser() {
    delete this.userParams.account;
    delete this.userParams.name;
    this.queryUser(null);
  }

  queryGroup(event: any) {
    const current: number = this.groupParams.current || 1;
    const size: number = this.groupParams.size || 10;
    this.http.get(`${Api.BaseGroupApi}/page/${current}/${size}`, this.groupParams).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.groupPage = res.data;
      }
    });
  }

  queryUser(event: any) {
    const current: number = this.userParams.current || 1;
    const size: number = this.userParams.size || 10;
    if (event && event.id) {
      this.userParams.groupId = event.id;
    }
    this.http.get(`${Api.BaseUserApi}/page/${current}/${size}`, this.userParams).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.userPage = res.data;
        if (this.userPage && !this.userPage.records) this.userPage.records = [];
      }
    });
  }

  addGroup() {
    this.modal.createStatic(GroupComponent).subscribe(() => this.queryGroup(null));
  }

  changeUserStatus(id: string, active: boolean) {
    this.http.put(`${Api.BaseUserApi}/${id}/${active}`).subscribe((res: any) => {
      if (res) {
        if (res.code === ResponseCode.SUCCESS) {
          this.msg.success(active ? '启用成功' : '禁用成功');
          this.queryUser(null);
        } else {
          this.msg.warning(res.message);
        }
      } else {
        this.msg.error('失败，未知错误');
      }
    });
  }

  deleteGroup(record: any) {
    if (record && record.id) {
      this.http.delete(`${Api.BaseGroupApi}/${record.id}`).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msg.success('删除成功');
            this.queryGroup(null);
          } else {
            this.msg.warning(res.message);
          }
        } else {
          this.msg.error('删除失败，未知错误');
        }
      });
    }
  }

  deleteUser(record: any) {
    if (record && record.id) {
      this.http.delete(`${Api.BaseUserApi}/${record.id}`).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msg.success('删除成功');
            this.queryUser(null);
          } else {
            this.msg.warning(res.message);
          }
        } else {
          this.msg.error('删除失败，未知错误');
        }
      });
    }
  }

  resetUserPassword(record: any) {
    if (record && record.id) {
      this.http.put(`${Api.BaseUserApi}/password/reset/${record.id}`).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msg.success('重置成功');
          } else {
            this.msg.warning(res.message);
          }
        } else {
          this.msg.error('重置失败，未知错误');
        }
      });
    }
  }

  addUser() {
    this.modal.createStatic(UserEditComponent).subscribe(() => this.queryUser(null));
  }
}
